package cn.jjxx.modules.common.jcaptcha;

import cn.jjxx.core.utils.CacheUtils;
import cn.jjxx.core.utils.JeewebPropertiesUtil;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 生成验证码
 *
 * @author www.jjxxkj.cn
 *
 */
public class JCaptchaFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		response.setDateHeader("Expires", 0L);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");
		String id = request.getRequestedSessionId();
		//BufferedImage bi = JCaptcha.captchaService.getImageChallengeForID(id);
		ServletOutputStream out = response.getOutputStream();
		try {
//			String verdcode = JxJcaptcha.generateVerifyCode(4).toLowerCase();
//			JxJcaptcha.outputImage(140, 60, out, verdcode);

			int JxJcaptchaLen = Integer.parseInt(JeewebPropertiesUtil.getConfig("JxJcaptchaLen"));
			int JxJcaptchaSize = Integer.parseInt(JeewebPropertiesUtil.getConfig("JxJcaptchaSize"));

			String verdcode = JxJcaptcha.generateVerifyCode(JxJcaptchaLen).toLowerCase();
			CacheUtils.put("verifyCode"+id,verdcode);
			JxJcaptcha.outputImage(140, JxJcaptchaSize, out, verdcode);
			//ImageIO.write(bi, "jpg", out);
			out.flush();
		} finally {
			out.close();
		}
	}
}